#include <BLDC.h>
#include <Comm.h>

// 2Byte PWM duty
#define BUF_SIZE 2

static byte buf[BUF_SIZE];
static DataFrame df;


void setup() {
  Serial.begin(115200);
  DF_Init(&df, buf, BUF_SIZE, BUF_SIZE);
  BLDC_Init();
  Serial.println(Serial.availableForWrite());
}


void loop() {
  BLDC_Update();
  
  status_t ret = -1;
  if (Serial.available()) {
    int ch = Serial.read();
    ret = DF_Feed(&df, ch);
    Serial.write(df.buf, df.received);
  }

  if (RECV_DONE == ret) {
    int val = bsToS16(buf, 0);
    if (val >=0 ) {
      BLDC_SetDir(MotorForward);
      BLDC_SetPwmDuty(val);
    }
    else {
      BLDC_SetDir(MotorBackward);
      BLDC_SetPwmDuty(-val);
    }
    
    Serial.print("set to "); Serial.println(val);
  }
}
